<template>
  <el-dialog
    :title="title"
    :close-on-click-modal="false"
    v-model="open"
    width="70%"
    append-to-body
    class="form-search"
  >
    <el-form
      v-if="open"
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
    >
      <SearchTool
        :code="{
          factory: 'factory',
          workshop: 'workShopCode',
          line: 'lineCode',
          section: 'sectionCode',
        }"
        :titles="{
          factory: '工厂',
          workshop: '工段',
          line: '产线',
          section: '工艺段',
        }"
        v-model:factory="queryParams.factory"
        v-model:workshop="queryParams.workShopCode"
        v-model:line="queryParams.lineCode"
        v-model:section="queryParams.sectionCode"
        :showFactory="false"
      ></SearchTool>
      <el-form-item label="线边仓" prop="storehouseCode">
        <StoreSelect
          v-model="queryParams.storehouseCode"
          :line="queryParams.lineCode"
          :section="queryParams.sectionCode"
          placeholder="请选择线边仓"
        ></StoreSelect>
      </el-form-item>
      <el-form-item label="批次号" prop="batchNo">
        <el-input
          v-model="queryParams.batchNo"
          placeholder="请输入批次号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="物料名称" prop="matName">
        <el-input
          v-model="queryParams.matName"
          placeholder="请输入物料名称"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <div class="flex gap-2" v-if="multiple" style="margin-bottom: 10px">
      <el-tag
        @close="tagClose(tag)"
        v-for="tag in arrSelection"
        :key="tag.matCode"
        closable
        style="margin-right: 5px; margin-top: 5px"
      >
        {{ tag.matName }}
      </el-tag>
    </div>
    <el-table
      v-loading="loading"
      :data="tableData"
      maxHeight="500px"
      border
      ref="matTable"
      show-overflow-tooltip
      @select="handleSelectionChange"
      @select-all="selectAll"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="物料/产品编号" align="center" prop="matCode"></el-table-column>

      <el-table-column label="物料/产品名称" align="center" prop="matName" />
      <el-table-column label="批次号" align="center" prop="batchNo" />
      <el-table-column label="工段" align="center" prop="workshopName" />
      <el-table-column label="产线" align="center" prop="lineName" />
      <el-table-column label="工艺段" align="center" prop="sectionName" />
      <el-table-column label="线边仓" align="center" prop="storehouseName" />
      <el-table-column label="库位" align="center" prop="binName" />
      <!-- <el-table-column label="库存" align="center" prop="num" /> -->
      <el-table-column label="可用库存" align="center" prop="availableNum" />
      <el-table-column label="单位" align="center" prop="packageUnit" />
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup name="MatDialog">
import { listStock } from "@/api/warehouse/stock";
import { toRefs, ref, reactive, watch } from "vue";
import {floatSub} from "@/utils/mathCount"
const open = defineModel("show");
const loading = ref(true);
const showSearch = ref(true);
const tableData = ref([]);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
// const selectData = defineModel();
const matTable = ref("matTable");
const arrSelection = ref([]);
const total = ref(0);
const title = ref("");
const queryRef = ref("queryRef");
const props = defineProps({
  value: {
    type: Array,
    default: () => [],
  },
  factory: {
    type: String,
    default: "",
  },
});
const { factory, value: selectData } = toRefs(props);
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    equipNo: undefined,
    matName: undefined,
    status: undefined,
  },
});

const { queryParams } = toRefs(data);
watch(
  () => factory,
  (newValue) => {
    queryParams.value.factory = newValue;
  },
  { immediate: true }
);

watch(
  () => open.value,
  (newValue) => {
    arrSelection.value = [];
    if (newValue && selectData.value.length) {
      selectData.value.forEach((item) => {
        arrSelection.value.push({
          randomId: `${item.matCode}_${item.batchNo}_${item.moveFrontWorkshopCode}_${item.moveFrontWarehouse}`,
          matCode: item.matCode,
          matName: item.matName,
          batchNo: item.batchNo,
          packageUnit: item.packageUnit,
          measureUnit: item.measureUnit,
          packing: item.packing,
          moveFrontStockNum: item.num,
          moveNum: item.num,
          workShopCode: item.moveFrontWorkSection,
          workshopName: item.moveFrontWorkSectionName,
          lineCode: item.moveFrontPdcLine,
          lineName: item.moveFrontPdcLineName,
          sectionCode: item.moveFrontProcessSection,
          sectionName: item.moveFrontProcessSectionName,
          storehouseCode: item.moveFrontWorkshopCode,
          storehouseName: item.moveFrontWorkshopName,
          binCode: item.moveFrontWarehouse,
          binName: item.moveFrontWarehouseName,
          erpOrderNo: item.erpOrderNo,
        });
      });
    }
    getList();
  }
);

const emit = defineEmits(["change"]);

/** 查询字典类型列表 */
function getList() {
  loading.value = true;
  listStock(queryParams.value).then((response) => {
    response.rows.forEach((item) => {
      item.randomId = `${item.matCode}_${item.batchNo}_${item.storehouseCode}_${item.binCode}`;
    });
    tableData.value = response.rows;
    total.value = response.total;
    loading.value = false;
    if(tableData.value.length ){
      tableData.value.forEach((item) => {
        item.availableNum = floatSub(item.num,item.frozenNum)
      });
    }
    nextTick(() => {
      if (tableData.value.length && arrSelection.value.length) {
        tableData.value.forEach((item) => {
          const include = arrSelection.value.filter((info) => info.randomId == item.randomId);
          if (include.length) {
            matTable.value.toggleRowSelection(item, true);
          }
        });
      }
    });
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryRef.value.resetFields();
  handleQuery();
}

/** 选择条数  */
function handleSelectionChange(selection, row) {
  let selected = selection.length && selection.indexOf(row) !== -1;
  console.log(selected); // 判断操作时  true就是选中，0或者false是取消选中
  if (selected) {
    arrSelection.value.push({
      randomId: row.randomId,
      matCode: row.matCode,
      matName: row.matName,
      batchNo: row.batchNo,
      packageUnit: row.packageUnit,
      measureUnit: row.measureUnit,
      packing: row.packing,
      num: row.num,
      num: row.num,
      workShopCode: row.workShopCode,
      workshopName: row.workshopName,
      lineCode: row.lineCode,
      lineName: row.lineName,
      sectionCode: row.sectionCode,
      sectionName: row.sectionName,
      storehouseCode: row.storehouseCode,
      storehouseName: row.storehouseName,
      binCode: row.binCode,
      binName: row.binName,
      erpOrderNo: row.erpOrderNo,
      frozenNum: row.frozenNum,
    });
  } else {
    arrSelection.value = arrSelection.value.filter((item) => item.randomId != row.randomId);
  }

  ids.value = selection.map((item) => item.randomId);
  single.value = selection.length != 1;
}
// 全选 或全不选
function selectAll(section) {
  if (section.length) {
    // 全选  push
    section.forEach((item) => {
      arrSelection.value.push({
        randomId: `${item.matCode}_${item.batchNo}_${item.storehouseCode}_${item.binCode}`,
        matCode: item.matCode,
        matName: item.matName,
        batchNo: item.batchNo,
        packageUnit: item.packageUnit,
        measureUnit: item.measureUnit,
        packing: item.packing,
        num: item.num,
        num: item.num,
        workShopCode: item.workShopCode,
        workshopName: item.workshopName,
        lineCode: item.lineCode,
        lineName: item.lineName,
        sectionCode: item.sectionCode,
        sectionName: item.sectionName,
        storehouseCode: item.storehouseCode,
        storehouseName: item.storehouseName,
        binCode: item.binCode,
        binName: item.binName,
        erpOrderNo: item.erpOrderNo,
        frozenNum: item.frozenNum,
      });
    });
  } else {
    // 全不选  当页数据  删除
    if (tableData.value.length && arrSelection.value.length) {
      tableData.value.forEach((item) => {
        arrSelection.value = arrSelection.value.filter((info) => item.randomId != info.randomId);
        // matTable.value.toggleRowSelection(item, true);
      });
    }
  }
  arrSelection.value = uniqueObjects(arrSelection.value);
}

function tagClose(tag) {
  arrSelection.value = arrSelection.value.filter((item) => item.randomId != tag.randomId);
  // 删除之后把表格中的勾选 去掉
  if (tableData.value.length) {
    tableData.value.forEach((item) => {
      const include = arrSelection.value.filter((info) => info.randomId == item.randomId);
      if (include.length) {
        matTable.value.toggleRowSelection(item, true);
      } else {
        matTable.value.toggleRowSelection(item, false);
      }
    });
  }
}

function submitForm() {
  open.value = false;
  selectData.value = arrSelection.value;
  emit("change", arrSelection.value);
}
</script>

<style lang="scss" scoped></style>
